package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/*
 * 自定义通用类型转换器：
 *     String类型 转成 枚举类型(是 BaseEnum衍生的所有的实现类(枚举类))
 *
 * 1. (String)Object Object必须能转成 String类型，否则报 ClassCastException
 * 2. Object.toString() Object不能为 null，否则报 NullPointerException
 * 3. String.valueof() 规避了以上两种方法的弊端，建议使用
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return  new Converter<String, T>() {
            @Override
            public T convert(String source) {
                // getEnumConstans() 获取枚举类的所有常量
                for (T enumConstant : targetType.getEnumConstants()) {
                     if(source.equals(String.valueOf(enumConstant.getCode()))){
                           return  enumConstant;
                     }
                }
                return null;
            }
        };
    }

    /*
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                for (T enumConstant : targetType.getEnumConstants()) {
                    // 使用 toString()必须保证 enumConstant不能为 null
                    if (source.equals(enumConstant.toString())) {
                        return enumConstant;
                    }
                }
                return null;
            }
        };
    }
    */
}
